<template>
  <SideBar @plus="plus" @changeToOldView="changeToOldBusiness" @submenuSelect='submenuSelect' @menuItemClick="menuItemClick" :normalData="normalData" :sideBarData="sideBarData" :showMask = 'isNoediting'></SideBar>
</template>
<script>
  import SideBar from '@/components/public-modules/side-bar/index'
  import {utilExtend, deepClone, getFormatDateTime} from '@/utils/m7Utils'
  import {throttle} from 'lodash'
  export default {
    name: 'Sidebar',
    data () {
      return {
        normalData: {
          'title': '工单管理',
          'showDropDown': true,
          'jumpArr': [
            {'jumpUrl': '/index/business/customSearch', 'text': this.$t('customer.CustomerSearch.CustomizeFastSearch'), show: true},
            {'jumpUrl': '/index/business/exportTask', 'text': ' ' + this.$t('webchat.exportTaskList'), show: true}
          ]
        },
        sideBarData: {
          'defaultActive': 'business_undeal@',
          'submenuArr': [
            {'submenuTitle': '', menu: [], type: 'business_undeal@'}, 
            {'submenuTitle': '', menu: [], type: 'business_my@'},
            {'submenuTitle': '', menu: [], type: 'business_all@'}
          ]
        }
      }
    },
    beforeMount () {
      this.refreshCustomSearch()
    },
    computed: {
      undealTitle () {
        let roleNum = this.$store.state.business.roleNum
        if (roleNum > 99) {
          roleNum = '99+'
        }
        return this.$t('business.undealBusiness') + '(' + roleNum + ')'
      },
      myTitle () {
        let total = this.$store.state.business.total
        let noReadNum = this.$store.state.business.noReadNum
        if (total > 99) {
          total = '99+'
        }
        if (noReadNum > 99) {
          noReadNum = '99+'
        }
        return this.$t('business.myTodo') + '(' + noReadNum + '/' + total + ')'
      },
      allTitle () {
        return this.$t('business.allBusiness')
      },
      isNoediting () {
        return this.$store.state.business.isNoediting
      }
    },
    methods: {
      plus (value) {
        this.$store.commit('business/SET_BUSINESS_IS_SHOW_BOX', {isShow: true})
        let path = value
        this.$router.push({path: path})
      },
      changeToOldBusiness () {
        this.$store.commit('IS_NEW_CARD_STYLE', {type: 'business', data: false})
        this.$store.dispatch('updateViewSwitch', {module: 'business', status: 'old'})
      },
      refreshCustomSearch:throttle(function(type){
        return this.$store.dispatch('queryQuickSearchListAll', {}).then((res) => {
          let obj = {}
          let all = [
            {label: this.$t('public.createTime'), value: 'none', disabled: true, condition: {}},
            {label: this.$t('webchat.today'), value: 'time__today', condition: {}},
            {label: this.$t('webchat.yesterday'), value: 'time__yesterday', condition: {}},
            {label: this.$t('webchat.lastWeek'), value: 'time__week', condition: {}},
            {label: this.$t('webchat.lastMonth'), value: 'time__month', condition: {}},
            {label: this.$t('webchat.oneYear'), value: 'time__oneYear', condition: {}},
            {label: this.$t('webchat.lastYear'), value: 'time__lastYear', condition: {}},
            {label: this.$t('business.weekParticipated'), value: 'time__week__participated', condition: {processMember: this.$store.state.session.sessionId, quickSearch: true}},
            {label: this.$t('business.weekFollowdeAgent'), value: 'time__week__followdeAgent', condition: {searchType: 'myFollowedBusiness', quickSearch: true}},
            {label: this.$t('business.weekCreated'), value: 'time__week__created', condition: {createUser: this.$store.state.session.sessionId, quickSearch: true}}
          ]
          if (this.$store.state.iframeMessage.showBusinessCreateTime) {
            all.splice(7, 0, {label: this.$t('webchat.threeYear'), value: 'time__threeYear', condition: {}})
          }
          let businessType = this.$store.state.business.transCache.businessTypes
          let undeal = [
            {label: this.$t('public.all'), value: '', condition: {flow: ''}},
            // ...businessType
          ]
          let my = [
            {label: this.$t('public.all'), value: '', condition: {flow: ''}},
            {label: this.$t('business.laterProcess'), value: 'laterProcess', condition: {laterProcess: true}},
            {label: this.$t('business.myTemp'), value: 'temp', condition: {saveFlag: 'temp'}},
            {label: this.$t('business.backBusiness'), value: 'isBack', condition: {isBack:true}, sortClass: 'sortClass'},
            //...businessType
          ]
          let selectObj = {all: '', my: '', undeal: ''}
          obj = {undeal, my, all}
          if (res.success) {
            let list = res.data || []
            list.forEach((item) => {
              if(item.type){
                item.condition.customSearch = 'customSearch'
                item.condition.type = item.type
              }
              obj[item.menu].push({label: item.name, value: item._id, condition: item.condition})
              selectObj[item.menu] = (selectObj[item.menu] === '' && item.default === 'true') ? item._id : selectObj[item.menu]
            })
          }
          this.sideBarData.submenuArr[0].menu = obj.undeal || []
          this.sideBarData.submenuArr[1].menu = obj.my || []
          this.sideBarData.submenuArr[2].menu = obj.all || []
          this.sideBarData.submenuArr[0].submenuTitle = this.undealTitle
          this.sideBarData.submenuArr[1].submenuTitle = this.myTitle
          this.sideBarData.submenuArr[2].submenuTitle = this.allTitle
          console.log(this.sideBarData);
          //查询暂存工单、退回工单、稍后处理工单数量
          let master = this.$store.state.session.sessionId
          let temp = this.$store.dispatch('queryAllBusinessCount', {queryCount: true, master, saveFlag: 'temp'});
          let laterProcess = this.$store.dispatch('queryAllBusinessCount', {queryCount: true, master, laterProcess: true});
          let back= this.$store.dispatch('queryAllBusinessCount',{queryCount:true,master,isBack:true});
          Promise.all([temp, laterProcess,back]).then(([tempNum, laterNum,backNum])=> {
            this.sideBarData.submenuArr.forEach(ele=>{
              if(ele.type == "business_my@"){
                //我的待办里添加计数
                ele.menu.forEach(item=>{
                  if(item.value == 'laterProcess'){
                    item.label = item.label + `(${laterNum.count > 99 ? 99 + '+' : laterNum.count})`
                  }else if(item.value == 'temp'){
                    item.label = item.label + `(${tempNum.count > 99 ? 99 + '+' : tempNum.count})`
                  }else if(item.value =='isBack'){
                    item.label = item.label + `(${backNum.count > 99 ? 99 + '+' : backNum.count})`
                  }
                })
              }
            })
          })
          if( type && type == 'refresh') return
          this.submenuSelect('business_undeal@')
          this.menuItemClick(this.sideBarData.submenuArr[0].menu[0], 'business_undeal')
        })
      },500,{trailing: false}),
      handlerQuickSelect (value, condition, activeName) {
        let type = value.split('__')
        let queryData = condition
        if (type[0] === 'time') {
          let time = this.searchDataReturn(type[1])
          utilExtend(queryData, time)
        }
        queryData.morePage = 1
        queryData.page = 1
        this.getBusiness(this.$store, activeName, queryData)
      },
      /*
      * 快捷搜索时间
      * */
      searchDataReturn (value) {
        let nowTime = new Date()
        let mtDate = nowTime.getTime()
        let startTime = ''
        let endTime = getFormatDateTime(new Date()).split(' ')[0] + ' 23:59:59'
        if (value === 'week') {
          // 近一周
          startTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24 * 6)).split(' ')[0] + ' 00:00:00'
        } else if (value === 'today') {
          // 今天
          startTime = getFormatDateTime(new Date(mtDate)).split(' ')[0] + ' 00:00:00'
        } else if (value === 'yesterday') {
          // 昨天
          startTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24)).split(' ')[0] + ' 00:00:00'
          endTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24)).split(' ')[0] + ' 23:59:59'
        } else if (value === 'month') {
          // 近一月
          startTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24 * 29)).split(' ')[0] + ' 00:00:00'
        } else if (value === 'oneYear') {
          let year = nowTime.getFullYear()
          startTime = year + '-01-01 00:00:00'
        } else if (value === 'lastYear') {
          let year = nowTime.getFullYear() - 1
          startTime = year + '-01-01 00:00:00'
          endTime = year + '-12-31 23:59:59'
        } else if (value === 'threeYear') {
          let threeYear = new Date()
          threeYear.setFullYear(nowTime.getFullYear() - 3)
          startTime = getFormatDateTime(threeYear)
        } else {
          endTime = ''
        }
        let searchQuery = {
          createTime$begin: startTime,
          createTime$end: endTime
        }
        return searchQuery
      },
      submenuSelect (value) {
        this.$set(this.sideBarData, 'defaultActive', value)
      },
      menuItemClick (item, activeName) {
        if(item.condition&&item.condition.stepFlow){
          delete item.condition.stepFlow
        }
        if (activeName === 'business_all@' && item.value === 'none') {
          return
        }
        if (activeName.indexOf('@') > -1) {
          activeName = activeName.replace('@', '')
        }
        this.handlerQuickSelect(item.value, item.condition, activeName)
      },
      getBusiness (store, tabName, data) {
        this.allCount = 0
        let action = 'queryAllBusiness'
        let sessionId = this.$store.state.session.sessionId
        if (tabName === 'business_my') {
          data.flag = 'kf'
          data.menu = 'my'
          //快捷搜索为多选，这边默认加上的status和master数组处理
          if(data.type){
            data.status = ['dealing']
            data.master = [sessionId]
          }else{
            data.status = 'dealing'
            data.master = sessionId
          }
        } else if (tabName === 'business_all') {
          data.menu = 'all'
          data.flag = 'kf'
        } else {
          data.flag = 'kf'
          data.menu = 'undeal'
          data.master = ''
          //快捷搜索为多选，这边默认加上的status数组处理，master默认空不处理
          if(data.type){
            data.status = ['dealing']
          }else{
            data.status = 'dealing'
          }
        }
        data.followedAgents = ''
        if (data.searchType === 'myFollowedBusiness') {
          data.followedAgents = sessionId
        } else if (data.searchType === 'temp') {
          data.saveFlag = 'temp'
          data.master = sessionId
        }
        // 如果工单参与人是我
        if (data.searchType === 'myParticipated') {
          data.myParticipated = true
//          delete data.menu
        }
        let _qu = deepClone(data)
        let queryNew = deepClone(data)
        delete _qu.searchType
        delete queryNew.searchType
        _qu.queryCount = true
        this.qu = _qu
        this.quAction = action + 'Count'
        this.$store.commit('business/SET_BUSINESS_TYPE', tabName)
        this.$store.commit('business/GET_BUSINESS_QUERY', queryNew)
        this.$store.commit('business/GET_FIRST_BUSINESS_QUERY', queryNew)
        if (!this.$store.state.business.showNewBusinessRouterBox) {
          this.$store.commit('business/SET_BUSINESS_IS_SHOW_BOX', {isShow: false})
        }
      }
    },
    components: {
      SideBar
    },
    watch: {
      '$store.state.business.refreshMenuBar'(val){
        //防止后台未处理完数据就开始统计，添加半秒延迟
        setTimeout(() => {
          this.refreshCustomSearch('refresh')
        },500)
      },
      '$store.state.business.businessSlideListRefresh' () {
        this.refreshCustomSearch()
      },
      '$store.state.business.operationNewBusinessObj' (data) {
        if (data.flag === 'toCard') {
          let index = 0
          let arrIndex = 1
          let defaultActive =  data.active + '@'
          if (data.active === 'business_all') {
            arrIndex = 2
            index = 3
            defaultActive = 'business_all@time__week'
          }
          this.sideBarData.defaultActive = defaultActive
          this.menuItemClick(this.sideBarData.submenuArr[arrIndex].menu[index], data.active)
        } else if (data.flag === 'selectSide') {
          this.$set(this.sideBarData, 'defaultActive', data.active + '@')
        }
      },
      undealTitle (cur) {
        this.sideBarData.submenuArr[0].submenuTitle = cur
      },
      myTitle (cur) {
        this.sideBarData.submenuArr[1].submenuTitle = cur
      },
      allTitle (cur) {
        this.sideBarData.submenuArr[1].submenuTitle = cur
      }
    }
  }
</script>
<style lang="stylus">
  @import "../../../assets/common.styl"
  .business-sidebar
    .router-link-active
      li
        color $c-main !important
        background-color #dddee0 !important
</style>
<style lang="stylus">
  @import "../../../assets/common.styl"
  .slideBar-box
    overflow hidden
    border-right 1px solid #ccc
  .operation
    .iconfont
      font-size 18px
      margin 0 2px 0
      color #606266
      cursor pointer
    .icon-gengduo
      font-size 19px
  .sidebar-top
    border-bottom 1px solid #ccc
    padding 0px 6px 0px 15px
    height 40.5px
    line-height 43px
    display flex
    justify-content space-between
  .business-sidebar
    text-align left
    position relative
    background-color #f0f2f3
    width 188px
    height calc(100vh - 90px)
    float left
    .side-scroll
      height calc(100vh - 90px)
    .el-menu
      background-color #f0f2f3
    .sidebar__title
      color #a0a9ad
      padding 10px 0
      border-bottom 1px solid #444c4f
    .el-menu__first
      font-weight bold
    .el-submenu
      .el-menu
        .el-menu-item
          padding-left 20px !important
        .el-menu-item:hover,.el-menu-item:focus
          color $c-main
          background-color #dddee0
    .sidebar-menu > .el-menu__first a li
      padding 15px 0px
      color $cf-gray0
    .sidebar-menu > .el-submenu
      color $cf-gray0
    .sidebar-menu .el-submenu li
      font-weight normal
      color #424242
    .sidebar-menu
      padding-top 5px
      margin-bottom 54px
    .el-menu-item
      height 45px
      line-height 14px
    .el-submenu__title
      height 44px
      line-height 44px
      font-weight bold
      color #000
     .el-submenu__title:hover,.el-submenu__title:focus
       color $c-main
       background-color #dddee0
     .el-submenu .el-menu .el-menu-item
       padding: 8px 0px;
       min-width: 100%;
       height: 30px;
     .config-sidebar__bottom
       position: absolute;
       width: 100%;
       height: 54px;
       bottom: 0px;
       z-index 2;
       background-color: #f5f6f7;
       border-top: 1px solid #e0e0e0;
       box-shadow: 0px -4px 6px -4px rgba(128,128,128,0.2);
       .config-sidebar__bottom-a
         background-color: #459ae9;
         color: #fff;
         border-radius: 4px;
         padding: 3px 7px;
      .el-menu-item:hover, .el-menu-item:focus
        color $c-main !important
        background-color #dddee0
        font-weight bold
</style>
